package org.millioncall.yueyoga.admin.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.DateTimeUtils;
import org.millioncall.openplatform.util.StringUtils;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.dao.entity.ClassEntity;
import org.millioncall.yueyoga.admin.dao.entity.ScheduleEntity;
import org.millioncall.yueyoga.admin.export.AbstractExcelExportTemplate;
import org.millioncall.yueyoga.admin.export.ClassExportTemplate;
import org.millioncall.yueyoga.admin.model.AviatorExpression;
import org.millioncall.yueyoga.admin.model.Chedule;
import org.millioncall.yueyoga.admin.model.CheduleDetails;
import org.millioncall.yueyoga.admin.model.ClassMemberModel;
import org.millioncall.yueyoga.admin.model.ClassProduct;
import org.millioncall.yueyoga.admin.model.ClassRecord;
import org.millioncall.yueyoga.admin.model.ClassScheduleModel;
import org.millioncall.yueyoga.admin.model.Coach;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.GroupUserModel;
import org.millioncall.yueyoga.admin.model.Place;
import org.millioncall.yueyoga.admin.model.Product;
import org.millioncall.yueyoga.admin.model.Status;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.model.Week;
import org.millioncall.yueyoga.admin.service.CheduleService;
import org.millioncall.yueyoga.admin.service.ClazzService;
import org.millioncall.yueyoga.admin.service.CoachService;
import org.millioncall.yueyoga.admin.service.MemberService;
import org.millioncall.yueyoga.admin.service.PlaceService;
import org.millioncall.yueyoga.admin.service.ProductService;
import org.millioncall.yueyoga.admin.service.StatusService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.millioncall.yueyoga.common.GlobalConstants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

@Controller
public class ClazzAction extends BaseAction {
	private static final String CLASS_SEARCH = "class_search";
	private static final String CLASS_ADD = "class_add";
	private static final String CLASS_UPDATE = "class_update";

	private ClazzService clazzService;
	private StatusService statusService;
	private ProductService productService;
	private PlaceService placeService;
	private CoachService coachService;
	private CheduleService cheduleService;
	private UserService userService;
	private MemberService memberService;

	private DateTimeUtils dtu = DateTimeUtils.getInstance();

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public StatusService getStatusService() {
		return statusService;
	}

	public void setStatusService(StatusService statusService) {
		this.statusService = statusService;
	}

	public ClazzService getClazzService() {
		return clazzService;
	}

	public void setClazzService(ClazzService clazzService) {
		this.clazzService = clazzService;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public PlaceService getPlaceService() {
		return placeService;
	}

	public void setPlaceService(PlaceService placeService) {
		this.placeService = placeService;
	}

	public CoachService getCoachService() {
		return coachService;
	}

	public void setCoachService(CoachService coachService) {
		this.coachService = coachService;
	}

	public CheduleService getCheduleService() {
		return cheduleService;
	}

	public void setCheduleService(CheduleService cheduleService) {
		this.cheduleService = cheduleService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/** 高级搜索班级 */
	@RequestMapping(value = "/ajaxAdvSearchClazz.jhtml")
	public void advSearchMember(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String strLimit = request.getParameter("limit");

		String exp = request.getParameter("expression");
		String expType = request.getParameter("expType");

		String msg = "";

		int limit = Integer.MAX_VALUE;

		try {
			limit = Integer.parseInt(strLimit);
		} catch (NumberFormatException e) {
			limit = Integer.MAX_VALUE;
		}

		if (StringUtils.isBlank(exp)) {
			msg = "{'success':false, 'msg':'表达式不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		if (StringUtils.isBlank(expType)) {
			msg = "{'success':false, 'msg':'表达式类型不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		// 用于过滤会员的条件map
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("hallcode", this.getUser(request).getOrganizationId());

		// 条件表达式
		// 在此组装条件表达式
		AviatorExpression expression = new AviatorExpression();
		expression.setExpression(exp);
		// 条件表达式的map
		Map<String, Object> aviatorParams = new HashMap<String, Object>();
		aviatorParams.put(GlobalConstants.RESULT_ROW_MODEL_KEY, expType);

		List<ClassRecord> clazz = this.clazzService.getAllClazzWithAviator(params, expression,
				aviatorParams, limit);

		if (clazz.size() > 0) {
			String json = JSON.toJSONStringWithDateFormat(clazz, "yyyy-MM-dd HH:mm:ss",
					SerializerFeature.WriteDateUseDateFormat);
			msg = "{'success':true, 'total':'" + clazz.size() + "', 'items':" + json + "}";
		} else {
			msg = "{'success':true, 'total':'0', 'items':''}";
		}

		WebAppUtils.ajaxResponse(response, msg);
	}

	/**
	 * 导出班级查询
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/exportClass.jhtml", method = RequestMethod.POST)
	public void exportClasses(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		Map<String, Object> map = new HashMap<String, Object>();

		// 获得参数
		String name = request.getParameter("name");
		String strState = request.getParameter("state");
		String assignedTo = request.getParameter("assignedTo");
		String placement = request.getParameter("placement");
		String strProductId = request.getParameter("productId");
		String mainTeacherId = request.getParameter("mainTeacher");
		String classType = request.getParameter("classType");// 班级类型

		// 设置班级名称
		if (!StringUtils.isBlank(name)) {
			map.put("name", name);
		}

		// 设置班级状态
		if (!StringUtils.isBlank(strState)) {
			map.put("state", strState);
		}

		// 设置班级负责人
		if (!StringUtils.isBlank(assignedTo)) {
			map.put("assignedToId", assignedTo);
		}

		// 设置场地
		if (!StringUtils.isBlank(placement)) {
			map.put("placeId", placement);
		}

		// 设置产品编号
		if (!StringUtils.isBlank(strProductId)) {
			map.put("productId", strProductId);
		}

		// 设置老师编号
		if (StringUtils.isNotBlank(mainTeacherId)) {
			map.put("mainTeacherId", mainTeacherId);
		}

		// 设置班级类型
		if (StringUtils.isNotBlank(classType)) {
			map.put("classType", classType);
		}

		List<Chedule> pl = this.clazzService.findScheduleExportPage(map);

		ClassExportTemplate template = new ClassExportTemplate(pl);

		response.setContentType(AbstractExcelExportTemplate.EXCEL_TYPE);
		AbstractExcelExportTemplate.setFileDownloadHeader(request, response, "班级信息表.xlsx");

		try {
			template.doExport(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** 搜索页查询所有 */
	@RequestMapping(value = "/searchClass.jhtml")
	public String findAllClasses(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		super.initFrontHeader(request, model);
		String display = request.getParameter("display");
		if ("block".equals(display)) {
			model.put("display", "block");
		}
		int start = 0;
		int limit = 10;
		int page = 1;
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		if (pageSize != null) {
			limit = Integer.parseInt(pageSize);
		}

		if (StringUtils.isNotBlank(pageNo)) {
			try {
				page = Integer.parseInt(pageNo);
			} catch (NumberFormatException e) {
				page = 1;
			}
			start = (page - 1) * limit;
		}

		Map<String, Object> map = new HashMap<String, Object>();

		// 获得参数
		String name = request.getParameter("name");
		String strState = request.getParameter("state");
		String assignedTo = request.getParameter("assignedTo");
		String placement = request.getParameter("placement");
		String strProductId = request.getParameter("productId");
		String mainTeacherId = request.getParameter("mainTeacher");
		String classType = request.getParameter("classType");// 班级类型

		String startClassDate = request.getParameter("startClassDate");
		String endClassDate = request.getParameter("endClassDate");

		model.put("name", name);
		model.put("state", strState);
		model.put("assignedTo", assignedTo);
		model.put("placement", placement);
		model.put("productId", strProductId);
		model.put("mainTeacher", mainTeacherId);
		model.put("classType", classType);

		model.put("startClassDate", startClassDate);
		model.put("endClassDate", endClassDate);

		// 设置班级名称
		if (!StringUtils.isBlank(name)) {
			map.put("name", name);
		}

		// 设置班级状态
		if (!StringUtils.isBlank(strState)) {
			map.put("state", strState);
		}

		// 设置班级负责人
		if (!StringUtils.isBlank(assignedTo)) {
			map.put("assignedToId", assignedTo);
		}

		// 设置场地
		if (!StringUtils.isBlank(placement)) {
			map.put("placeId", placement);
		}

		// 设置产品编号
		if (!StringUtils.isBlank(strProductId)) {
			map.put("productId", strProductId);
		}

		// 设置老师编号
		if (StringUtils.isNotBlank(mainTeacherId)) {
			map.put("mainTeacherId", mainTeacherId);
		}

		// 设置班级类型
		if (StringUtils.isNotBlank(classType)) {
			map.put("classType", classType);
		}
		// --产品开始时间
		if (StringUtils.isNotBlank(startClassDate)) {
			map.put("startClassDate", startClassDate);
		}
		// --产品结束时间
		if (StringUtils.isNotBlank(endClassDate)) {
			map.put("endClassDate", endClassDate);
		}

		// 获取所有产品
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		Map<String, Object> mapP = new HashMap<String, Object>();
		mapP.put("groups", groupIds);
		mapP.put("hallcode", this.getUser(request).getOrganizationId());
		List<Product> plProduct = this.productService.findProductAvailableAll(mapP);

		// 获取所有负责人
		List<GroupUserModel> listAssignedTo = this.userService.findUsersByGroupId("4", super
				.getUser(request).getOrganizationId());

		// 获取场地
		Map<String, Object> mapPlace = new HashMap<String, Object>();
		mapPlace.put("groups", groupIds);
		mapPlace.put("hallcode", this.getUser(request).getOrganizationId());
		List<Place> plPlace = this.placeService.findAllByOrganizationId(mapPlace);

		// 获取所有班级类型
		List<Status> classStatus = this.statusService.findByType(10);

		Map<String, Object> mapT = new HashMap<String, Object>();
		mapT.put("groups", groupIds);
		mapT.put("hallcode", this.getUser(request).getOrganizationId());
		// 获取所有老师
		List<Coach> teachers = this.coachService.findAllTeacherByOrganizationId(mapT);

		Map<String, Object> mapA = new HashMap<String, Object>();
		mapA.put("groups", groupIds);
		mapA.put("hallcode", this.getUser(request).getOrganizationId());
		List<Coach> coach1 = this.coachService.findAllAssistantByOrganizationId(mapA);
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<ClassRecord> pl = null;
		if ("block".equals(display)) {
			pl = this.clazzService.findClazzPage(start, limit, map);
			model.put("ClazzCount", pl.size());
		}

		model.put("pl", pl);
		model.put("plProduct", plProduct);
		model.put("plPlace", plPlace);
		model.put("assignedToList", listAssignedTo);
		model.put("classStatusList", classStatus);
		model.put("mainTeachers", teachers);
		model.put("coach1", coach1);

		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		calendar.set(Calendar.YEAR, year);
		int weeks = calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);

		// 设置第几周
		List<Week> listWeekYear = new ArrayList<Week>();
		Week week = null;
		for (int i = 1; i <= weeks; i++) {
			week = new Week();
			week.setId(i);
			week.setNameYear(String.valueOf(i));
			listWeekYear.add(week);
		}

		model.put("weekYearList", listWeekYear);

		if (name == null && (strState == null || strState == "0")
				&& (assignedTo == null || assignedTo == "0")
				&& (strProductId == null || strProductId == "0") && placement == null) {
			model.put("isBlank", "blank");
		} else {
			model.put("isBlank", "notBlank");
		}

		return CLASS_SEARCH;
	}

	/** 跳转到添加班级页面 */
	@RequestMapping(value = "/toAddClass.jhtml", method = RequestMethod.GET)
	public String toAddClass(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		super.initFrontHeader(request, model);
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		Map<String, Object> mapP = new HashMap<String, Object>();
		mapP.put("groups", groupIds);
		mapP.put("hallcode", this.getUser(request).getOrganizationId());
		List<Product> list = this.productService.findProductAvailableAll(mapP);

		Map<String, Object> mapPlace = new HashMap<String, Object>();
		mapPlace.put("groups", groupIds);
		mapPlace.put("hallcode", this.getUser(request).getOrganizationId());
		List<Place> listPlace = this.placeService.findAll(mapPlace);

		Map<String, Object> mapTeacher = new HashMap<String, Object>();
		mapTeacher.put("type", 0);
		mapTeacher.put("groups", groupIds);
		mapTeacher.put("hallcode", this.getUser(request).getOrganizationId());
		List<Coach> listCoach = this.coachService.findAll(mapTeacher);

		Map<String, Object> mapAssistant = new HashMap<String, Object>();
		mapAssistant.put("type", 1);
		mapAssistant.put("groups", groupIds);
		mapAssistant.put("hallcode", this.getUser(request).getOrganizationId());
		List<Coach> listHelpCoach = this.coachService.findAll(mapAssistant);

		List<GroupUserModel> listAssignedTo = this.userService.findUsersByGroupId("4", super
				.getUser(request).getOrganizationId());

		List<Status> classStatus = this.statusService.findByType(10);
		model.put("classStatusList", classStatus);
		model.put("productList", list);
		model.put("placeList", listPlace);
		model.put("coachList", listCoach);
		model.put("helpCoachList", listHelpCoach);
		model.put("assignedToList", listAssignedTo);
		return CLASS_ADD;
	}

	/** 添加班级 */
	@RequestMapping(value = "/addClass.jhtml", method = RequestMethod.POST)
	public void addClazz(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String msg;

		// 获得参数
		String name = request.getParameter("name");
		if (StringUtils.isBlank(name)) {
			msg = "{'success':false, 'msg':'班级名称不可为空!'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		String strType = request.getParameter("type");// 班级类型
		String strState = request.getParameter("state");// 班级状态
		String strAssignedTo = request.getParameter("assignedTo");// 负责人编号
		String remarks = request.getParameter("remarks");
		String[] schedule = request.getParameterValues("schedule[]");

		User user = this.getUser(request);
		ClassEntity entity = new ClassEntity();
		entity.setName(name);
		entity.setType(strType);
		Integer state = Integer.valueOf(strState);
		entity.setState(state);

		if (StringUtils.isBlank(strAssignedTo)) {
			strAssignedTo = null;
		}

		entity.setOfficerId(strAssignedTo);

		entity.setReamarks(remarks);
		entity.setBranchId(super.getUser(request).getOrganizationId());
		Date now = new Date();
		entity.setCreateTime(now);
		entity.setLastModifyTime(now);
		entity.setCreatedBy(super.getUser(request).getId());
		entity.setLastModifiedBy(super.getUser(request).getId());

		if (schedule != null) {
			List<ScheduleEntity> schedules = new ArrayList<ScheduleEntity>();
			for (String str : schedule) {
				ScheduleEntity obj = JSON.parseObject(str, ScheduleEntity.class);
				if (obj.getSeatNumber() == null || obj.getSeatNumber() == 0) {
					msg = "{'success':false, 'msg':'席位数不能为空或为0!'}";
					WebAppUtils.ajaxResponse(response, msg);
					return;
				}
				schedules.add(obj);
			}
			entity.setSchedules(schedules);
		}

		// 注：此时课程信息的id和classId都为空
		boolean b;
		try {
			entity.setOrganizationid(user.getOrganizationId());
			b = this.clazzService.saveClassSaveEntity(entity);
		} catch (Exception e) {
			msg = "{'success':false, 'msg':'创建班级失败!'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		if (b) {
			msg = "{'success':true, 'msg':'创建班级成功!','classId':'" + entity.getId() + "'}";
			WebAppUtils.ajaxResponse(response, msg);
		} else {
			msg = "{'success':false, 'msg':'创建班级失败!'}";
			WebAppUtils.ajaxResponse(response, msg);
		}
	}

	/** 跳转到修改班级页面 */
	@RequestMapping(value = "/toUpdateClass.jhtml", method = RequestMethod.GET)
	public String toUpdateClazz(HttpServletRequest request, ModelMap model) {
		super.initFrontHeader(request, model);
		String strId = request.getParameter("classId");
		int id = Integer.valueOf(strId);

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		Map<String, Object> mapP = new HashMap<String, Object>();
		mapP.put("groups", groupIds);
		mapP.put("hallcode", this.getUser(request).getOrganizationId());
		List<Product> list = this.productService.findProductAvailableAll(mapP);

		Map<String, Object> mapPlace = new HashMap<String, Object>();
		mapPlace.put("groups", groupIds);
		mapPlace.put("hallcode", this.getUser(request).getOrganizationId());
		List<Place> listPlace = this.placeService.findAll(mapPlace);

		Map<String, Object> mapTeacher = new HashMap<String, Object>();
		mapTeacher.put("type", 0);
		mapTeacher.put("groups", groupIds);
		mapTeacher.put("hallcode", this.getUser(request).getOrganizationId());
		List<Coach> listCoach = this.coachService.findAll(mapTeacher);

		Map<String, Object> mapAssistant = new HashMap<String, Object>();
		mapAssistant.put("type", 1);
		mapAssistant.put("groups", groupIds);
		mapAssistant.put("hallcode", this.getUser(request).getOrganizationId());
		List<Coach> listHelpCoach = this.coachService.findAll(mapAssistant);

		List<GroupUserModel> listAssignedTo = this.userService.findUsersByGroupId("4", super
				.getUser(request).getOrganizationId());

		List<Status> classStatus = this.statusService.findByType(10);
		model.put("classStatusList", classStatus);
		model.put("productList", list);
		model.put("placeList", listPlace);
		model.put("coachList", listCoach);
		model.put("helpCoachList", listHelpCoach);
		model.put("officerList", listAssignedTo);
		model.put("classId", strId);// 班级编号

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("groups", groupIds);
		map.put("id", id);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		ClassEntity entity = this.clazzService.findByClassId(map);
		model.put("name", entity.getName());
		model.put("type", entity.getType());
		model.put("state", entity.getState());

		model.put("officerId", entity.getOfficerId());
		model.put("remarks", entity.getReamarks());

		List<List<ScheduleEntity>> weekSchedules = new ArrayList<List<ScheduleEntity>>();
		for (int i = 0; i < 7; i++) {
			weekSchedules.add(new ArrayList<ScheduleEntity>());
		}
		for (ScheduleEntity e : entity.getSchedules()) {
			weekSchedules.get(e.getWeek() - 1).add(e);
		}
		model.put("schedules", weekSchedules);

		return CLASS_UPDATE;
	}

	/** 修改班级 */
	@RequestMapping(value = "/updateClass.jhtml", method = RequestMethod.POST)
	public void updateClass(HttpServletRequest request, HttpServletResponse response) {
		String msg;

		// 获得参数
		String strId = request.getParameter("id");
		String name = request.getParameter("name");

		if (StringUtils.isBlank(name)) {
			msg = "{'success':false, 'msg':'班级名称不可为空'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		String strType = request.getParameter("type");// 班级类型
		String strState = request.getParameter("state");// 班级状态
		String strAssignedTo = request.getParameter("assignedTo");// 负责人编号
		String remarks = request.getParameter("remarks");
		String[] schedule = request.getParameterValues("schedule[]");

		ClassEntity entity = new ClassEntity();
		entity.setId(Integer.valueOf(strId));
		entity.setName(name);
		entity.setType(strType);
		Integer state = Integer.valueOf(strState);
		entity.setState(state);

		if (StringUtils.isBlank(strAssignedTo)) {
			strAssignedTo = null;
		}

		entity.setOfficerId(strAssignedTo);

		entity.setReamarks(remarks);
		entity.setBranchId(super.getUser(request).getOrganizationId());
		Date now = new Date();
		entity.setLastModifyTime(now);
		entity.setLastModifiedBy(super.getUser(request).getId());

		if (schedule != null) {
			List<ScheduleEntity> schedules = new ArrayList<ScheduleEntity>();
			for (String str : schedule) {
				ScheduleEntity obj = JSON.parseObject(str, ScheduleEntity.class);
				obj.setClassId(entity.getId());
				if (obj.getId() == null || obj.getId() == 0) {
					schedules.add(obj);
				}
			}
			entity.setSchedules(schedules);
		}

		boolean b;
		try {
			b = this.clazzService.updateClassEntity(entity);
		} catch (Exception e) {
			e.printStackTrace();
			msg = "{'success':false, 'msg':'修改班级失败'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		if (b) {
			msg = "{'success':true, 'msg':'修改班级成功'}";
			WebAppUtils.ajaxResponse(response, msg);
		} else {
			msg = "{'success':false, 'msg':'修改班级失败'}";
			WebAppUtils.ajaxResponse(response, msg);
		}
	}

	/**
	 * 查看班级信息
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/viewClass.jhtml")
	public String viewClass(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		super.initFrontHeader(request, model);

		String classId = request.getParameter("classId");
		if (StringUtils.isBlank(classId)) {
			model.put("msg", "无效的班级编号");
			return "redirect:searchClass.jhtml";
		}

		Integer intId;
		try {
			intId = Integer.valueOf(classId);
		} catch (NumberFormatException e) {
			model.put("msg", "无效的班级编号");
			return "redirect:searchClass.jhtml";
		}

		int start = 0;
		int limit = 10;
		int page = 1;
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");
		if (pageSize != null) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			try {
				page = Integer.parseInt(pageNo);
			} catch (NumberFormatException e) {
				page = 1;
			}
			start = (page - 1) * limit;
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		Map<String, Object> mapP = new HashMap<String, Object>();
		mapP.put("groups", groupIds);
		mapP.put("hallcode", this.getUser(request).getOrganizationId());
		List<Product> list = this.productService.findProductAvailableAll(mapP);

		// 所有会员
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		map.put("classId", intId);
		List<ClassMemberModel> allMembers = this.memberService.findClassMember(map);

		List<Status> classStatus = this.statusService.findByType(10);

		Map<String, Object> mapPlace = new HashMap<String, Object>();
		mapPlace.put("groups", groupIds);
		mapPlace.put("hallcode", this.getUser(request).getOrganizationId());
		List<Place> listPlace = this.placeService.findAll(mapPlace);

		Map<String, Object> mapTeacher = new HashMap<String, Object>();
		mapTeacher.put("type", 0);
		mapTeacher.put("groups", groupIds);
		mapTeacher.put("hallcode", this.getUser(request).getOrganizationId());
		List<Coach> listCoach = this.coachService.findAll(mapTeacher);

		Map<String, Object> mapAssistant = new HashMap<String, Object>();
		mapAssistant.put("type", 1);
		mapAssistant.put("groups", groupIds);
		mapAssistant.put("hallcode", this.getUser(request).getOrganizationId());
		List<Coach> listHelpCoach = this.coachService.findAll(mapAssistant);

		List<GroupUserModel> listAssignedTo = this.userService.findUsersByGroupId("4", super
				.getUser(request).getOrganizationId());

		model.put("classStatusList", classStatus);
		model.put("productList", list);
		model.put("allMembers", allMembers);

		map.put("id", intId);

		ClassEntity clazz = this.clazzService.findByClassId(map);
		model.put("classId", classId);
		model.put("classEntity", clazz);
		List<List<ScheduleEntity>> weekSchedules = new ArrayList<List<ScheduleEntity>>();
		for (int i = 0; i < 7; i++) {
			weekSchedules.add(new ArrayList<ScheduleEntity>());
		}
		for (ScheduleEntity e : clazz.getSchedules()) {
			weekSchedules.get(e.getWeek() - 1).add(e);
		}
		model.put("schedules", weekSchedules);

		if (clazz.getType().equals("固定会员")) {
			String searchKeywords = request.getParameter("memberKeywords");

			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("classId", clazz.getId());
			map2.put("keywords", searchKeywords);
			map2.put("groups", groupIds);
			map2.put("hallcode", this.getUser(request).getOrganizationId());
			PaginatedList<ClassMemberModel> classMembers = this.clazzService
					.findClassMembersByClassId(map2, start, limit);

			model.put("classMembers", classMembers);
		} else if (clazz.getType().equals("不定会员")) {
			// do nothing for now
		}

		map.put("classId", clazz.getId());
		List<ClassProduct> classProducts = this.clazzService.findClassProduct(map);
		model.put("classProducts", classProducts);
		model.put("placeList", listPlace);
		model.put("coachList", listCoach);
		model.put("helpCoachList", listHelpCoach);
		model.put("assignedToList", listAssignedTo);
		String tabIndex = request.getParameter("tabIndex");
		if (StringUtils.isNotBlank(tabIndex)) {
			model.put("tabIndex", tabIndex);
		}
		return "class_detail";
	}

	/**
	 * 向班级中添加会员
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/addMemberToClass.jhtml", method = RequestMethod.POST)
	public void addMemberToClass(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String msg = null;
		String strClassId = request.getParameter("classId");
		String strMemberId = request.getParameter("memberId");
		Integer intClassId = Integer.valueOf(strClassId);
		Integer intMemberId = Integer.valueOf(strMemberId);

		boolean b = this.clazzService.containsMember(intClassId, intMemberId);
		if (b) {// 该会员在此班级中已存在
			msg = "{success:false,msg:'该会员在班级中已存在'}";
		} else {
			boolean success = this.clazzService.addMemberToClass(intClassId, intMemberId, super
					.getUser(request).getId());
			if (success) {// 添加成功
				msg = "{success:true,msg:'会员添加成功'}";
			} else {
				msg = "{success:false,msg:'会员添加失败'}";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	@RequestMapping(value = "/addProductToClass.jhtml", method = RequestMethod.POST)
	public void addProductToClass(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String msg = null;
		String strClassId = request.getParameter("classId");
		String strProductId = request.getParameter("productId");
		String strProductName = request.getParameter("productName");
		Integer intClassId = Integer.valueOf(strClassId);
		Integer intProductId = Integer.valueOf(strProductId);

		boolean b = this.clazzService.containsProduct(intClassId, intProductId);
		if (b) {
			msg = "{success:false,msg:'该产品已存在'}";
		} else {
			boolean success = this.clazzService.addProductToClass(intClassId, intProductId,
					strProductName, super.getUser(request).getId());
			if (success) {// 添加成功
				msg = "{success:true,msg:'产品添加成功'}";
			} else {
				msg = "{success:false,msg:'产品添加失败'}";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);

	}

	/**
	 * 删除班级中的会员
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/deleteMemberOfClass.jhtml", method = RequestMethod.POST)
	public void deleteMemberOfClass(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String msg = "{success:true,msg:'删除成功'}";
		String strClassId = request.getParameter("classId");
		String[] strMemberIds = request.getParameterValues("ids[]");

		Integer intClassId = Integer.valueOf(strClassId);
		if (strMemberIds != null && strMemberIds.length > 0) {
			List<Integer> intMemberIds = new ArrayList<Integer>();
			for (String memberId : strMemberIds) {
				intMemberIds.add(Integer.valueOf(memberId));
			}
			boolean b = this.clazzService.deleteMemberOfClass(intClassId, intMemberIds);
			if (b) {
				msg = "{success:true,msg:'删除会员成功'}";
			} else {
				msg = "{success:false,msg:'删除会员失败'}";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	@RequestMapping(value = "/deleteProductOfClass.jhtml", method = RequestMethod.POST)
	public void deleteProductOfClass(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String msg = "{success:true,msg:'删除成功'}";
		String strClassId = request.getParameter("classId");
		String[] strProductIds = request.getParameterValues("ids[]");

		Integer intClassId = Integer.valueOf(strClassId);
		if (strProductIds != null && strProductIds.length > 0) {
			List<Integer> intProductIds = new ArrayList<Integer>();
			for (String productId : strProductIds) {
				intProductIds.add(Integer.valueOf(productId));
			}
			boolean b = this.clazzService.deleteProductOfClass(intClassId, intProductIds);
			if (b) {
				msg = "{success:true,msg:'删除会员成功'}";
			} else {
				msg = "{success:false,msg:'删除会员失败'}";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 删除班级 */
	@RequestMapping(value = "/deleteClass.jhtml", method = RequestMethod.POST)
	public void deleteClass(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String msg;
		String[] arrIds = request.getParameterValues("ids[]");

		List<String> strIds = Arrays.asList(arrIds);
		List<Integer> intIds = new ArrayList<Integer>();
		for (String strId : strIds) {
			intIds.add(Integer.valueOf(strId));
		}

		int i = this.clazzService.deleteClazzByIds(intIds);
		msg = i > 0 ? "success" : "failure";
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 根据班级ID查询班级课程表信息 */
	@RequestMapping(value = "/ajaxGetScheduleList.jhtml")
	public void findClassSchedules(String clsId, String curDate, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String msg = "{'success':false,items:" + "" + "}";
		if (StringUtils.isNotBlank(curDate) && StringUtils.isNotBlank(clsId)) {
			Date date = dtu.parse(curDate, "yyyy-M-d");
			// --上一页
			Date prvDate = dtu.addDay(date, -7);
			String prvDateStr = dtu.format(prvDate, "yyyy-M-d");
			// --下一页
			Date nexDate = dtu.addDay(date, 7);
			String nexDateStr = dtu.format(nexDate, "yyyy-M-d");
			List<ClassScheduleModel> pl = clazzService.findClassScheduleList(date, clsId);
			String scheduleItems = JSON.toJSONString(pl);
			msg = "{'success':true,curDate:'" + curDate + "',prvDate:'" + prvDateStr
					+ "',nexDate:'" + nexDateStr + "',items:" + scheduleItems + "}";
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 根据课程Id删除课程信息 */
	@RequestMapping(value = "/ajaxDelScheduleById.jhtml")
	public void deleteClassSchedule(String kcxh, String curDate, String scheduleId,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String msg = "{success:false,msg:'删除课程失败!'}";
		if (StringUtils.isBlank(scheduleId) && StringUtils.isBlank(kcxh)
				|| StringUtils.isBlank(curDate)) {
			msg = "{success:false,msg:'删除课程失败!'}";
		} else {
			if (cheduleService.deleteScheduleByCdts(kcxh, scheduleId, curDate)) {
				msg = "{success:true,msg:'删除课程成功!'}";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 根据班级编号、日期、及其他数据添加课程信息 */
	@RequestMapping(value = "/ajaxAddSchedule.jhtml")
	public void addSchedule(String curDate, String clsId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String msg = "";
		if (StringUtils.isBlank(clsId)) {
			msg = "{success:false,msg:'创建课程失败!'}";
		} else {

		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 根据课程Id日期开启订座 */
	@RequestMapping(value = "/ajaxReservations.jhtml")
	public void ajaxReservations(String kcxh, String curDate, String scheduleId,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String msg = "{success:false,msg:'开启预定失败!'}";
		if ((StringUtils.isBlank(scheduleId) || StringUtils.isBlank(kcxh))
				&& (StringUtils.isBlank(curDate))) {
			msg = "{success:false,msg:'开启预定失败!'}";
		} else {
			if (cheduleService.reservateSeat(kcxh, scheduleId, curDate)) {
				msg = "{success:true,msg:'开启预定成功!'}";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 添加课程信息 */
	@RequestMapping(value = "/ajaxAddScheduleDetail.jhtml")
	public void ajaxAddScheduleDetail(String classId, String scheduleTime, String startTime,
			String endTime, String teacherId, String assistantId, String placeId,
			String scheduleName, String seatNumber, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String msg = "";
		if (StringUtils.isBlank(classId) || StringUtils.isBlank(scheduleTime)
				|| StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
			msg = "{success:false,msg:'创建课程失败!'}";
		} else {
			CheduleDetails sd = new CheduleDetails();
			sd.setClassId(Integer.valueOf(classId));
			sd.setCheduleTime(dtu.parse(scheduleTime, "yyyy-MM-dd"));
			sd.setStarttime(startTime);
			sd.setEndtime(endTime);
			sd.setName(scheduleName);
			sd.setState("未开启预定");
			if (StringUtils.isNotBlank(seatNumber)) {
				sd.setSeatNumber(Integer.valueOf(seatNumber));
			}
			sd.setIsReservation(0);
			if (StringUtils.isNotBlank(teacherId)) {
				sd.setTeacherId(Integer.valueOf(teacherId));
			}
			if (StringUtils.isNotBlank(assistantId)) {
				sd.setAssistantId(Integer.valueOf(assistantId));
			}
			if (StringUtils.isNotBlank(placeId)) {
				sd.setPlaceId(Integer.valueOf(placeId));
			}
			if (cheduleService.addScheduleDetail(sd)) {
				msg = "{success:true,msg:'创建课程成功!'}";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 添加课程信息 */
	@RequestMapping(value = "/ajaxDeleteScheduleByScheduleId.jhtml")
	public void ajaxDeleteScheduleByScheduleId(String scheduleId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String msg = "{success:false,msg:'删除课程失败!'}";
		if (StringUtils.isNotBlank(scheduleId)) {
			try {
				Integer id = Integer.valueOf(scheduleId);
				if (cheduleService.deleteByPrimaryKey(id) > 0) {
					msg = "{success:true,msg:'删除课程成功!'}";
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}
}
